package com.ctw.mall.service.impl;

import com.ctw.mall.dao.UserMapper;
import com.ctw.mall.enums.RoleEnum;
import com.ctw.mall.pojo.User;
import com.ctw.mall.service.IUserService;
import com.ctw.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static com.ctw.mall.enums.ResponseEnum.*;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param user
     */
   @Override
   public ResponseVo<User> register(User user){

       //用户名，邮箱不能重复
       int countByUsername = userMapper.countByUsername(user.getUsername());
       if(countByUsername>0){
           return ResponseVo.error(USERNAME_EXIST);
       }

       int countByEmail = userMapper.countByEmail(user.getEmail());
       if(countByEmail>0){

           return ResponseVo.error(EMAIL_EXIST);
       }

       user.setRole(RoleEnum.CUSTOMER.getCode());

       //密码用MD5消息散列,摘要算法(没有秘钥)(Spring自带)
       //返回值为byte的数组
       user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if(resultCount == 0){
           return ResponseVo.error(ERROR);
        }

        return ResponseVo.success();
    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        User user= userMapper.selectByUsername(username);
        if(user==null){
            //此处不提示用户不存在，避免透露数据库信息，一般提示用户或者密码错误
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        //传入的password和数据库内的比较，数据库内的使用了MD5，传入的也需要处理
        if(!user.getPassword().equalsIgnoreCase(
                DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
            //密码错误
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }

        user.setPassword("");
        //若直接返回查找到的对象会返回密码,在返回前设置为空
        return ResponseVo.success(user);
    }


}
